package org.openstack.service.auth;

import org.openstack.common.constants.AuthConstants;
import org.openstack.model.auth.Authentication;
import org.openstack4j.api.OSClient.OSClientV3;
import org.openstack4j.model.common.Identifier;
import org.openstack4j.openstack.OSFactory;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

/**
 * Created by jiyun on 2017/8/2.
 */
public class AuthOS {

    private static Logger logger = LoggerFactory.getLogger(AuthOS.class);


    /**
     * 线程本地变量实现
     * 提高并发效率
     */
    private static ThreadLocal<OSClientV3> osHolder = new ThreadLocal<>();

    public static OSClientV3 getOSClient() {
        OSClientV3 os = osHolder.get();
        try {
            if (os == null) {
                os = OSFactory.builderV3().endpoint(AuthConstants.AUTH_URL)
                        .credentials(AuthConstants.USERNAME, AuthConstants.PASSWORD, Identifier.byName(AuthConstants.DOMAIN))
                        .scopeToProject(Identifier.byName(AuthConstants.PROJECT_NAME), Identifier.byName(AuthConstants.DOMAIN))
                        .authenticate();
            }
        } catch (Exception e) {
            logger.error("Authentication Fail! Check configure in auth.properties or the OpenStack KeyStone Service.", e);
        }
        return os;
    }

    public static OSClientV3 getOSClient(Authentication user) {
        OSClientV3 os = osHolder.get();
        try {
            if (os == null) {
                os = OSFactory.builderV3().endpoint(user.getAuthURL())
                        .credentials(user.getUserName(), user.getPassword(), Identifier.byName(user.getDomain()))
                        .scopeToProject(Identifier.byName(user.getProjectName()), Identifier.byName(user.getDomain()))
                        .authenticate();
            }
        } catch (Exception e) {
            logger.error("Authentication Fail! Check configure in auth.properties or the OpenStack KeyStone Service.", e);
        }
        return os;
    }

    /**
     * 单例模式实现
     * 阻塞线程
     */
//    private volatile static OSClientV3 os;
//
//    public static OSClientV3 getInstance() {
//        try {
//            if (os == null) {
//                synchronized (AuthOS.class) {
//                    os = OSFactory.builderV3().endpoint(AuthConstants.AUTH_URL)
//                            .credentials(AuthConstants.USERNAME, AuthConstants.PASSWORD, Identifier.byName(AuthConstants.DOMAIN))
//                            .scopeToProject(Identifier.byId(AuthConstants.PROJECT_ID)).authenticate();
//                }
//            }
//        } catch (Exception e) {
//            logger.error("Authentication Fail! Check configure in auth.properties or the OpenStack KeyStone Service.", e);
//        }
//        return os;
//    }
}
